package ucuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserRewardListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserRewardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserRewardListLogic {
	return &GetUserRewardListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 获取用户奖励列表
func (l *GetUserRewardListLogic) GetUserRewardList(in *pb.GetUserRewardListReq) (*pb.GetUserRewardListResp, error) {
	defer utils.RecoverPanic()

	var ugs *usercenter.UserRewardStat
	var err error
	ugs, err = l.svcCtx.UserRewardStatModel.FindOne(l.ctx, in.Uid)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	var rsp pb.GetUserRewardListResp
	rsp.List = make([]*pb.UserReward, 0)
	rsp.Total = ugs.Total
	rsp.NotReceived = ugs.NotReceived

	if ugs.NotReceived > 0 {
		var list []*usercenter.UserReward
		list, err = l.svcCtx.UserRewardModel.Find(l.ctx, in.Uid, 0, userkey.RewardStateCreated, in.PageNo, in.PageSize)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}

		if len(list) <= 0 {
			return &rsp, nil
		}
		for i := 0; i < len(list); i++ {
			vl := pb.UserReward{
				Id:           list[i].Id,
				Uid:          list[i].Uid,
				RewardType:   list[i].RewardType,
				RewardAmount: list[i].RewardAmount,
				CreateTime:   list[i].CreateTime.Format(dbkey.DateTimeCNFormat),
				ActivityId:   list[i].ActivityId,
			}
			vl.Title, vl.Content = userkey.GetRewardTitleAndContent(list[i].ActivityId)
			rsp.List = append(rsp.List, &vl)
		}
	}

	return &rsp, nil
}
